<template>
	<view class="manage-store" :style="[{background: backgroundImage}]">
		<view id="header" class="header">
			<u-navbar title="场地管理" @leftClick="leftClick" :bgColor="bgColor" :titleStyle="titleStyle"
				:leftIconColor="leftIconColor"></u-navbar>
			<view class="search u-m-t-38">
				<u-search placeholder="请输入场地关键字" v-model="page.storeName" :show-action="false"
					@change="change"></u-search>
			</view>
		</view>
		<scroll-view scroll-y @scrolltolower="reachBottom" class="scroll-list" :style="{height:scrollerHeight + 'px'}">
			<view class="list u-font-26">
				<view class="item" v-for="(item,index) in siteList" :key="index">
					<view class="title-containers">
						<view>
							<view class="title-font">
								<text>{{item.storeName}}</text>
								<text class="device-count">{{item.deviceCount}}台</text>
							</view>
							<view class="address-container">
								<text>{{item.province}}{{item.city}}{{item.district}}{{item.address}}</text>
								<text v-if="group == item.id" class="defult u-font-22">默认</text>
							</view>
						</view>
						<view class="cash-register-container" @click="collectionCode(item)">
							<u--image width="64rpx" height="64rpx"
								:src="`${baseStaticFileUrl}/image/merchant-store/offlineCollectionCode.png`" />
							<view class="text">下载收款码</view>
						</view>
					</view>

					<view class="line"></view>
					<view class="m-flex-row u-row-between">
						<u-radio-group v-model="group">
							<u-radio iconSize="13" labelSize="13" shape="circle" activeColor="#6072FF" label="设为默认"
								:name="item.id" @change="radioChange"></u-radio>
						</u-radio-group>
						<view class="m-flex-row" style="width: 280rpx;">
							<view class="m-flex-row  u-row-end" v-if="item.deviceCount==0" @click="delShowBtn(item.id)">
								<u--image width="21rpx" height="21rpx" :showLoading="true"
									:src="`${baseStaticFileUrl}/image/merchant-store/delete.png`" />
								<text>删除</text>
							</view>
							<view class="m-flex-row  u-row-end"
								@click="nav('/pages-other/merchant-store/add-merchant-store',item.id)">
								<u--image width="21rpx" height="21rpx" :showLoading="true"
									:src="`${baseStaticFileUrl}/image/merchant-store/edit.png`" />
								<text>编辑</text>
							</view>
						</view>


					</view>
				</view>
				<u-empty v-if="siteList.length == 0" text="暂无场地" mode="list"
					icon="http://cdn.uviewui.com/uview/empty/list.png" />
			</view>
		</scroll-view>
		<view id="add-view" class="add-view">
			<!-- <view class="add"> + 添加投放场地</view> -->
			<u-button shape="circle" :customStyle="nextStepBtnCustomStyle" text="添加投放场地"
				@click="nav('/pages-other/merchant-store/add-merchant-store',0)"></u-button>
		</view>
		<u-modal :show="delShow" title="提示" content="确定要删除该场地吗?" showCancelButton @cancel="delShow=false"
			@confirm="delConfirm"></u-modal>
		<u-modal :show="collectionCodeShow" :showConfirmButton="false">
			<view class="collection-code">
				<view class="title">线下收款码</view>
				<view class="img">
					<u--image width="400rpx" height="400rpx" :src="collectionCodeQr"></u--image>
				</view>
				<view class="tips">提示：下载后请打印并粘贴到场地收银台</view>
				<view class="operate-container">
					<u-button text="关闭"
						:customStyle="{width: '232rpx', height: '87rpx', borderRadius: '120rpx',margin:'0'}"
						@click="collectionCodeShow=false" />
					<u-button text="下载"
						:customStyle="{width: '232rpx', height: '87rpx', borderRadius: '120rpx',margin:'0'}"
						@click="downloadCode()" />
				</view>
			</view>
		</u-modal>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				nextStepBtnCustomStyle: {
					width: '688rpx',
					height: '88rpx',
					background: 'rgb(96,114,255)',
					borderRadius: '120px',
					color: '#fff',
				},
				bgColor: 'transparent',
				titleStyle: 'color:white',
				leftIconColor: 'white',
				baseStaticFileUrl: this.$configPath.staticFileUrl,
				backgroundImage: 'url(' + this.$configPath.staticFileUrl +
					'/image/merchant-store/merchant-store-bg.svg) no-repeat 0rpx 0rpx',
				group: 0,
				emptyTitle: '暂无场地',
				emptyContent: '',
				height: 0,
				// 从哪个页面来
				from: '',
				page: {
					pageNum: 1,
					storeName: ''
				},
				siteList: [],
				status: 'loadmore',
				scrollerHeight: 0,
				swiperContentHeight: 0,
				loadText: {
					loadmore: '轻轻上拉加载',
					loading: '稍等一会,正在努力为您加载...',
					nomore: '没有更多了'
				},
				delShow: false,
				//场地id
				msId: '',
				collectionCodeQr: '',
				collectionCodeShow: false,
				//二维码保存的文件名
				path: '',
			}
		},
		onLoad(option) {
			this.from = option.from;
		},
		onReady() {
			this.getPomHeight();
		},
		onShow() {
			this.change();
		},
		onPullDownRefresh() {
			this.change('refresh');
		},
		methods: {
			downloadCode() {
				let qrcode = this.collectionCodeQr.replace(/^data:image\/\w+;base64,/, ""); //去掉data:image/png;base64,
				let that = this;
				uni.getSetting({
					success: (res) => {
						console.log(res)
						if (!res.authSetting["scope.writePhotosAlbum"]) {
							uni.showModal({
								title: '警告',
								content: '检测到您没您未授权相册权限,点击确定获取授权。',
								success: function(res) {
									if (res.confirm) {
										uni.authorize({
											scope: 'scope.writePhotosAlbum',
											success() {
												// 用户已经同意
												that.saveImgToAlbum(qrcode);
											},
											fail(err) {
												console.log('用户拒绝授权相册')
											}
										})
									}
								}
							})
						} else {
							that.saveImgToAlbum(qrcode);
						}
					},
					fail: () => {
						console.log('点击了拒绝')
					}
				})
			},
			// 保存二维码图片到相册
			saveImgToAlbum(qrcode) {
				let that = this;
				var fileManager = uni.getFileSystemManager();
				fileManager.writeFile({
					filePath: wx.env.USER_DATA_PATH + this.path, // 指定图片的临时路径
					data: qrcode, // 要写入的文本或二进制数据
					encoding: 'base64', // 指定写入文件的字符编码
					success: res => {
						uni.saveImageToPhotosAlbum({ // 保存图片到相册
							filePath: wx.env.USER_DATA_PATH + that.path,
							success: function(res) {
								uni.showModal({
									title: '保存成功',
									content: '保存路径为:' + wx.env.USER_DATA_PATH + '文件夹下',
								});
							},
							fail: function(err) {
								console.log('保存失败', err)
							}
						})
					},
					file: err => {
						console.log('写入文件失败', err)
					}
				})
			},
			collectionCode(item) {
				this.path = '/' + item.storeName + '.png'
				this.$api('merchantStore.receiptQrCode', {
					id: item.id
				}).then(res => {
					if (res.status == 0) {
						this.collectionCodeQr = this.$mQrCode.createQrCodeImg(res.data, {
							size: parseInt(300) //二维码大小
						})
						console.log(this.collectionCodeQr)
						this.collectionCodeShow = true;
					}
				})
			},
			radioChange(id) {
				// console.log('radioChange', id);
				this.$api('merchantStore.updateDefaultStatus', {
					id: id
				}).then(res => {})
			},
			reachBottom() {
				// console.log("-------------下拉加载--------------")
				if (this.status == 'nomore') {
					return;
				}
				this.status = 'loading';
				// 使用延迟实现加载动画效果
				setTimeout(() => {
					this.page.pageNum = ++this.page.pageNum;
					this.siteListLoad();
					this.status = 'loadmore';
				}, 2000)
			},
			nav(url, siteId) {
				uni.navigateTo({
					url: url + '?from=' + this.from + '&siteId=' + siteId
				})
			},
			siteListLoad(type) {
				this.$api('merchantStore.findMerchantStoreList', this.page).then(res => {
					if (type === 'refresh') {
						uni.stopPullDownRefresh();
					}
					if (res.data != null) {
						this.siteList.push(...res.data.list)
						this.page.pageNum = res.data.pageNum;
						this.siteList.forEach(item => {
							if (item.defaultStatus) {
								this.group = item.id;
							}
						})
						if (this.page.pageNum >= res.data.pages) {
							this.status = 'nomore';
							return;
						}
					}
				})
			},
			// 返回上一页
			leftClick() {
				uni.navigateBack();
			},
			change(type) {
				this.page.pageNum = 1;
				this.status = 'loadmore';
				this.siteList = []
				this.siteListLoad(type);
			},
			updateDefaultStatus(id) {
				this.$api('merchantStore.updateDefaultStatus', {
					id: id
				}).then(res => {})
			},
			getPomHeight() {
				let query = wx.createSelectorQuery().in(this)
				query.select('#header').boundingClientRect()
				query.select('#add-view').boundingClientRect()
				query.exec(res => {
					let windowHeight = wx.getSystemInfoSync().windowHeight
					this.scrollerHeight = windowHeight
					for (var i = 0; i < res.length; i++) {
						if (res[i]) {
							this.scrollerHeight -= res[i].height;
						}
					}
				})
			},
			delShowBtn(id) {
				this.msId = id;
				this.delShow = true
			},
			delConfirm() {
				this.updateAsDelById()
				this.delShow = false
			},
			updateAsDelById() {
				let p = {
					id: this.msId
				}
				this.$api('merchantStore.updateAsDelById', p).then(res => {

					if (res.status == 0) {
						this.$helpers.toast('删除成功');
						this.change();
					} else {
						this.$helpers.toast('删除失败:' + res.msg);
					}
				})
			},

		}
	}
</script>

<style lang="scss">
	/deep/ .u-icon__icon {
		// font-size: 14px !important;
	}

	/deep/ .u-button--active {
		color: #ffffff !important;
		background: #6072FF !important;
	}

	.collection-code {
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		width: 100%;

		.img {
			margin-top: 85rpx;
		}

		.tips {
			color: rgba(0, 0, 0, 0.7);
			margin-top: 30rpx;
			font-size: 26rpx;
		}

		.operate-container {
			width: 100%;
			margin-top: 110rpx;
			display: flex;
			justify-content: space-between;
		}
	}

	.manage-store {
		height: 100vh;
		background-size: 100% 435rpx !important;
		background-repeat: no-repeat;

		/deep/ .u-modal__content__text {
			text-align: center;
		}

		.header {
			.search {
				display: flex;
				// flex-direction: column;
				align-items: center;
				height: 200rpx;
				// padding-top: 100rpx;
				padding: 100rpx 25rpx 0 25rpx;

				// /deep/.u-search {
				// 	width: 300rpx;
				// }
				text {
					color: rgb(255, 255, 255);
					margin-left: 15rpx;
					font-size: 26rpx;
				}
			}
		}

		.address-container {
			width: 450rpx;
			margin-top: 35rpx;
		}

		.title-containers {
			display: flex;
			justify-content: space-between;
			align-items: flex-start;
			width: 100%;

			.cash-register-container {
				display: flex;
				align-items: center;
				justify-content: center;
				flex-direction: column;

				.text {
					margin-top: 10rpx;
				}
			}
		}

		.title-font {
			color: rgba(0, 0, 0, 0.9);
			font-weight: 600;
		}

		.list {
			overflow: hidden;
			color: rgba(0, 0, 0, 0.7);
			box-sizing: border-box;

			.item {
				box-sizing: border-box;
				display: flex;
				flex-direction: column;
				justify-content: space-around;
				align-items: flex-start;
				margin: 0rpx 30rpx 30rpx;
				height: 295rpx;
				background-color: #FFFFFF;
				border-radius: 20rpx;
				padding: 20rpx 30rpx;

				.line {
					width: 635rpx;
					border: 1rpx solid rgba(0, 0, 0, 0.03);
				}

				.device-count {
					color: rgb(254, 64, 76);
					font-size: 22rpx;
					font-weight: 400;
					line-height: 40rpx;
					letter-spacing: 0.25999999046325684px;
					padding: 2rpx 14rpx;
					background-color: rgb(255, 240, 241);
					border-radius: 20rpx;
					margin-left: 10rpx;
				}

				.defult {
					color: rgb(96, 114, 255);
					font-weight: 400;
					line-height: 40rpx;
					letter-spacing: 0.26px;
					padding: 2rpx 14rpx;
					background: rgb(235, 241, 254);
					border-radius: 20rpx;
					margin-left: 10rpx;
				}

				/deep/.u-radio__icon-wrap {
					width: 26rpx !important;
					height: 26rpx !important;
				}

				.u-row-end {
					justify-content: flex-end !important;

					text {
						margin-left: 10rpx;
					}
				}
			}

		}

		.add-view {
			bottom: 0rpx;
			height: 120rpx;
			position: fixed;
			width: 100%;
			background: white;
			padding-top: 20rpx;
		}

	}
</style>